package com.wanmait.happyheating.interceptor;

import com.wanmait.happyheating.pojo.Admin;
import com.wanmait.happyheating.service.AdminService;
import com.wanmait.happyheating.util.AdminJWTUtils;
import com.wanmait.happyheating.util.IgnoreToken;
import com.wanmait.happyheating.util.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
@Component
public class AdminInterceptor implements HandlerInterceptor
{
    @Resource
    AdminService adminService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if(handler instanceof HandlerInterceptor){ return true; }
        System.out.println(handler+"-----");
        HandlerMethod handlerMethod=(HandlerMethod)handler;
        System.out.println("=====");
        Method method=handlerMethod.getMethod();
        if(method.isAnnotationPresent(IgnoreToken.class))
        {
            IgnoreToken ignoreToken = method.getAnnotation(IgnoreToken.class);
            if(ignoreToken.required()){
                return true;
            }
        }
        String token=request.getHeader("token");
        if(token.equals(null)){
            throw new Exception ("没有登录");
        }
        Integer id=Integer.parseInt(AdminJWTUtils.getAudience(token));
        Admin admin= adminService.getById(id);
        if(admin==null){
            throw new Exception("没有该管理员");
        }
        JWTUtils.verifyToken(token,admin.getPass());
        request.setAttribute("admin",admin);
        return true;
    }

}
